'use server'

import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { Decimal } from '@prisma/client/runtime/library'

interface ReturnData {
  saleId: number
  items: {
    saleItemId: number
    quantity: string
    reason: string
  }[]
}

export async function createReturn(data: ReturnData) {
  try {
    // 开始事务
    const result = await prisma.$transaction(async (tx) => {
      // 1. 获取销售单
      const sale = await tx.sale.findUnique({
        where: { id: data.saleId },
        include: {
          items: {
            include: {
              product: true
            }
          }
        }
      })

      if (!sale) {
        throw new Error('销售单不存在')
      }

      // 2. 验证退货数量
      for (const returnItem of data.items) {
        const saleItem = sale.items.find(item => item.id === returnItem.saleItemId)
        if (!saleItem) {
          throw new Error('销售单明细不存在')
        }

        const returnQuantity = parseInt(returnItem.quantity)
        if (returnQuantity <= 0) {
          continue // 跳过退货数量为0的商品
        }

        if (returnQuantity > saleItem.quantity) {
          throw new Error(`商品 ${saleItem.product.name} 退货数量不能大于销售数量`)
        }
      }

      // 3. 创建退货单
      const returnItems = data.items.filter(item => parseInt(item.quantity) > 0)
      const totalAmount = returnItems.reduce((sum, returnItem) => {
        const saleItem = sale.items.find(item => item.id === returnItem.saleItemId)!
        return sum + saleItem.price.mul(new Decimal(returnItem.quantity))
      }, new Decimal(0))

      const returnOrder = await tx.returnOrder.create({
        data: {
          code: `TH${Date.now()}`,
          saleId: sale.id,
          totalAmount,
          items: {
            create: returnItems.map(returnItem => {
              const saleItem = sale.items.find(item => item.id === returnItem.saleItemId)!
              return {
                saleItemId: returnItem.saleItemId,
                productId: saleItem.productId,
                quantity: parseInt(returnItem.quantity),
                price: saleItem.price,
                amount: saleItem.price.mul(new Decimal(returnItem.quantity)),
                reason: returnItem.reason
              }
            })
          }
        },
        include: {
          items: {
            include: {
              product: true
            }
          }
        }
      })

      // 4. 更新商品库存
      for (const returnItem of returnItems) {
        const saleItem = sale.items.find(item => item.id === returnItem.saleItemId)!
        await tx.product.update({
          where: { id: saleItem.productId },
          data: {
            stock: {
              increment: parseInt(returnItem.quantity)
            }
          }
        })
      }

      return returnOrder
    })

    // 序列化返回数据
    const serializedReturn = {
      ...result,
      totalAmount: result.totalAmount.toString(),
      items: result.items.map(item => ({
        ...item,
        price: item.price.toString(),
        amount: item.amount.toString(),
        product: {
          ...item.product,
          price: item.product.price.toString()
        }
      }))
    }

    revalidatePath('/dashboard/sales/returns')
    return { success: true, data: serializedReturn }
  } catch (error) {
    console.error('创建退货单失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '创建退货单失败'
    }
  }
}

export async function cancelReturn(returnId: number) {
  try {
    // 开始事务
    await prisma.$transaction(async (tx) => {
      // 1. 获取退货单
      const returnOrder = await tx.returnOrder.findUnique({
        where: { id: returnId },
        include: {
          items: true
        }
      })

      if (!returnOrder) {
        throw new Error('退货单不存在')
      }

      // 2. 恢复商品库存
      for (const item of returnOrder.items) {
        await tx.product.update({
          where: { id: item.productId },
          data: {
            stock: {
              decrement: item.quantity // 减少库存（撤销退货）
            }
          }
        })
      }

      // 3. 先删除退货单明细
      await tx.returnItem.deleteMany({
        where: {
          returnId: returnId
        }
      })

      // 4. 再删除退货单
      await tx.returnOrder.delete({
        where: { id: returnId }
      })
    })

    revalidatePath('/dashboard/sales/returns')
    return { success: true }
  } catch (error) {
    console.error('撤销退货失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '撤销退货失败'
    }
  }
} 